import type { onPageScroll as _onPageScroll, onPullDownRefresh as _onPullDownRefresh, onReachBottom as _onReachBottom } from '@dcloudio/uni-app';
import type MxpRefreshPage from '../../mxp-refresh-page/mxp-refresh-page.vue';
import { type Ref, ref } from 'vue';

/**
 * 刷新的hooks
 */
export function useRefresh(onPullDownRefresh?: typeof _onPullDownRefresh, onReachBottom?: typeof _onReachBottom) {
  const mxpRefreshPageRef = ref<InstanceType<typeof MxpRefreshPage>>();

  onPullDownRefresh?.(() => {
    mxpRefreshPageRef.value?.onPullDownRefresh();
  });
  onReachBottom?.(() => {
    mxpRefreshPageRef.value?.onReachBottom();
  });

  return {
    mxpRefreshPageRef,
  };
}

/**
 * 刷新的hooks (列表专用)
 */
export function useMescrollList(op: {
  onPageScroll: typeof _onPageScroll;
  onPullDownRefresh: typeof _onPullDownRefresh;
  onReachBottom?: typeof _onReachBottom;
}) {
  // 当前tab下标
  const currTabIndex = ref(0);
  const mxpRefreshPageRefs: Ref<InstanceType<typeof MxpRefreshPage>[]> = ref([]);
  const autoLaadObj = ref({ [currTabIndex.value]: true });
  const scrollMap: Record<number, number> = {};

  op.onPageScroll?.((e) => {
    scrollMap[currTabIndex.value] = e.scrollTop;
  });
  op.onPullDownRefresh?.(() => {
    mxpRefreshPageRefs.value[currTabIndex.value]?.onPullDownRefresh();
  });

  op.onReachBottom?.(() => {
    mxpRefreshPageRefs.value[currTabIndex.value]?.onReachBottom();
  });

  /**
   * 切换tab,恢复滚动条位置
   */
  function currTabIndexChange(index: number) {
    currTabIndex.value = index;
    autoLaadObj.value[index] = true;
    const refreshPageRef = mxpRefreshPageRefs.value[index];
    if (refreshPageRef) {
      // 恢复上次滚动条的位置
      uni.pageScrollTo({ scrollTop: scrollMap[index] || 0, duration: 0 });
      // 再次恢复上次滚动条的位置, 确保元素已渲染
      setTimeout(() => {
        uni.pageScrollTo({ scrollTop: scrollMap[index] || 0, duration: 0 });
      }, 20);
    }
  }

  return {
    autoLaadObj,
    mxpRefreshPageRefs,
    currTabIndex,
    currTabIndexChange,
  };
}
